#include "security_config.hpp"
#include "logger.hpp"
#include "clock.hpp"

namespace qOS {

// Static member initialization
uint32_t SecurityManager::securityViolations = 0;
uint32_t SecurityManager::intrusionAttempts = 0;
uint64_t SecurityManager::lastAuditTime = 0;
bool SecurityManager::securityInitialized = false;

// SecurityConfig static member definitions
const uint32_t SecurityConfig::MIN_HAMMING_DISTANCE;
const uint32_t SecurityConfig::TOKEN_ENTROPY_BITS;
const uint64_t SecurityConfig::TOKEN_TIMEOUT_US;
const uint32_t SecurityConfig::MAX_FAILURE_COUNT;
const uint32_t SecurityConfig::HIGH_EXECUTION_COUNT;
const uint64_t SecurityConfig::MIN_SLACK_TIME_US;
const uint64_t SecurityConfig::DEADLINE_WARNING_THRESHOLD;
const uint32_t SecurityConfig::AUDIT_INTERVAL_CYCLES;
const uint32_t SecurityConfig::SECURITY_LOG_LEVEL;
const bool SecurityConfig::ENABLE_INTRUSION_DETECTION;
const size_t SecurityConfig::MAX_STACK_USAGE_PERCENT;
const bool SecurityConfig::ENABLE_HEAP_PROTECTION;
const uint32_t SecurityConfig::MEMORY_CANARY_VALUE;

//==============================================================================
void SecurityManager::initialize()
{
    if (!securityInitialized) {
        logger::out(logger::info) << "SECURITY: Security manager initialization started";
        
        securityViolations = 0;
        intrusionAttempts = 0;
        lastAuditTime = clock::getTick();
        securityInitialized = true;
        
        logger::out(logger::info) << "SECURITY: Security manager initialized with min Hamming distance: " 
                                   << SecurityConfig::MIN_HAMMING_DISTANCE
                                   << ", token entropy: " << SecurityConfig::TOKEN_ENTROPY_BITS << " bits";
    }
}

//==============================================================================
void SecurityManager::reportViolation(FSCP_ErrorType violationType, const char* description)
{
    securityViolations++;
    
    logger::out(logger::error) << "SECURITY VIOLATION #" << securityViolations 
                             << " - Type: " << static_cast<uint32_t>(violationType)
                             << " - " << description;
    
    // Critical violation handling
    if (violationType == FSCP_ErrorType::SECURITY_BREACH) {
        intrusionAttempts++;
        logger::out(logger::error) << "SECURITY: Critical security breach detected - Total attempts: " 
                                 << intrusionAttempts;
        
        // Enhanced protection for repeated violations
        if (intrusionAttempts > 10) {
            logger::out(logger::error) << "SECURITY CRITICAL: System under attack - Entering safe mode";
            // Here you could implement additional protective measures
        }
    }
    
    // Automatic security audit on violations
    if (securityViolations % 5 == 0) {
        performAudit();
    }
}

//==============================================================================
bool SecurityManager::detectIntrusion()
{
    if (!SecurityConfig::ENABLE_INTRUSION_DETECTION) {
        return false;
    }
    
    uint64_t currentTime = clock::getTick();
    
    // Check for high frequency violations
    if (securityViolations > 50 && (currentTime - lastAuditTime < 1000000)) {
        logger::out(logger::error) << "SECURITY: High frequency violations detected - Possible intrusion";
        return true;
    }
    
    return false;
}

//==============================================================================
void SecurityManager::performAudit()
{
    lastAuditTime = clock::getTick();
    
    logger::out(logger::info) << "SECURITY: Performing scheduled audit - Violations: " 
                               << securityViolations 
                               << ", Intrusion attempts: " << intrusionAttempts;
    
    // System health assessment
    if (securityViolations > SecurityConfig::MAX_FAILURE_COUNT) {
        logger::out(logger::warning) << "SECURITY: High violation count detected - System health at risk";
    }
    
    // Check for attack patterns
    if (isUnderAttack()) {
        logger::out(logger::error) << "SECURITY: Attack pattern confirmed - Implementing countermeasures";
    }
}

//==============================================================================
uint32_t SecurityManager::getViolationCount()
{
    return securityViolations;
}

//==============================================================================
void SecurityManager::resetCounters()
{
    uint32_t oldViolations = securityViolations;
    securityViolations = 0;
    intrusionAttempts = 0;
    
    logger::out(logger::info) << "SECURITY: Counters reset - Previous violations: " << oldViolations;
}

//==============================================================================
bool SecurityManager::validateToken(uint64_t token)
{
    // Basic token validation
    if (token == 0) {
        logger::out(logger::error) << "SECURITY: Null token detected";
        return false;
    }
    
    // Token entropy check (basic)
    if (token < 0x1000) {  // Very low entropy token
        logger::out(logger::warning) << "SECURITY: Low entropy token detected: " 
                                   << token;
    }
    
    return true;
}

//==============================================================================
bool SecurityManager::isUnderAttack()
{
    // Multiple criteria for attack detection
    bool highViolations = securityViolations > SecurityConfig::MAX_FAILURE_COUNT;
    bool frequentIntrusions = intrusionAttempts > 5;
    bool highRateViolations = false;  // Could implement rate limiting here
    
    return highViolations || frequentIntrusions || highRateViolations;
}

} // namespace qOS